import uuid
import threading
import os
from typing import Optional
from datetime import datetime
import time
import lxconfig
from es import ElasticsearchStorage

my_data = threading.local()
my_data.trace_id = None
my_data.log_level = lxconfig.get('log_level',1)   # 0:DEBUG, 1:INFO, 2:ERROR
# 定义统一前缀打印函数

# 修改日志等级
def set_log_level(level):
    my_data.log_level = level

es = ElasticsearchStorage()
es.connect()

def set_trace_id(trace_id: Optional[str] = None) -> None:
    if trace_id is None:
        trace_id = str(uuid.uuid4()).replace('-', '')[:10]
    my_data.trace_id = trace_id


# 打印日志
def log(message,prefix='INFO'):
    if prefix == 'DEBUG' and my_data.log_level > 0:
        return
    if my_data.trace_id is None:
        my_data.trace_id = str(uuid.uuid4()).replace('-', '')[:10]
    now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    log_message = f"[{now}] [{prefix}] [{my_data.trace_id}] {message}"
    print(log_message)
    save_log(log_message)
    # 保存日志到es
    try:
        es.store_message({"serverName":"py","traceId":my_data.trace_id,"appName":"pyqywx","dtTime":int(time.time() * 1000),"content": message,"logLevel":prefix,"className":"","method":"","lineNumber":0,"firmId":"zysq"})
    except Exception as e:
        print(f"保存日志到es失败: {str(e)}")

def info(message):
    log(message,'INFO')

def debug(message):
    log(message,'DEBUG')

def error(message):
    log(message,'ERROR')

import queue

log_queue = queue.Queue()

def log_worker():
    while True:
        log_message = log_queue.get()
        if log_message is None:
            break
        log_file = datetime.now().strftime('%Y%m%d.log')
        with open(log_file, 'a', encoding='utf-8') as f:
            f.write(log_message + '\n')
        clear_log()
        log_queue.task_done()

log_thread = threading.Thread(target=log_worker)
log_thread.daemon = True
log_thread.start()

def save_log(log_message):
    log_queue.put(log_message)

def clear_log():
    # 清理七天前的日志文件
    now = datetime.now()
    for filename in os.listdir('.'):
        if filename.endswith('.log'):
            try:
                file_date = datetime.strptime(filename[:8], '%Y%m%d')
                if (now - file_date).days > 6:
                    os.remove(filename)
            except ValueError:
                continue